package com.qf.bookshop2.service.impl;

import com.qf.bookshop2.mapper.BookMapper;
import com.qf.bookshop2.mapper.UserMapper;
import com.qf.bookshop2.model.Book;
import com.qf.bookshop2.model.User;
import com.qf.bookshop2.service.IBuyBookService;
import com.qf.bookshop2.util.ExchangeMoneyOrNumException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.Exchanger;

@Service
public class BuyBookServiceImpl implements IBuyBookService {



    @Autowired
    UserMapper mapper1;
    @Autowired
    BookMapper mapper2;

    @Transactional   //事务控制
    @Override
    public void buyBooks(String username, Integer bid, Integer bnum) {

        bnum=1;

        //查询用户信息，获得金额
        User buyUser = mapper1.selectUserByUsername(username);
        //查询书籍信息，获得单价和库存
        Book sellBook = mapper2.selectBooksByBid(bid);
        //查书籍库存，并与购买量进行比较
        if (sellBook.getBnum().compareTo(bnum)<0){
            throw new ExchangeMoneyOrNumException("图书库存不足！");
        }
        BigDecimal n= new BigDecimal(bnum);
        //查人的余额
        if(buyUser.getBalance().compareTo(sellBook.getPrice().multiply(n))<0){
            throw new ExchangeMoneyOrNumException("账户余额不足！");
        }
        //修改库存
        sellBook.setBnum(sellBook.getBnum()-bnum);
        mapper2.updateBooksByBook(sellBook);
        //修改余额
        buyUser.setBalance(buyUser.getBalance().subtract(sellBook.getPrice().multiply(n)));
        mapper1.updateUserbyUser(buyUser);
    }

    @Transactional
    @Override
    public List<Book> getAllBooks() {
        return mapper2.selectAllBooks();
    }
}
